'use strict'

const Service = require('egg').Service

class DepartmentService extends Service {
  async getDepartmentList(queryInfo) {
    // 如果没有 queryInfo.pagenum，说明是获取全部（这个不要做默认值修改，因为其他模块会调用该接口获得所有部门数据）
    if (!queryInfo.pageNum) {
      let resultAll = await this.app.mysql.query('SELECT * FROM c_department ')

      return this.ctx.getRESTfulData(
        {
          total: resultAll.length,
          departmentList: resultAll,
        },
        '获取所有部门列表成功',
        200
      )
    }

    let resultAll = await this.app.mysql.query(
      `SELECT 
      *
      FROM c_department 
      WHERE departname like ?`,
      ['%' + queryInfo.keywords + '%']
    )

    let result = await this.app.mysql.query(
      `SELECT 
      *
      FROM c_department 
      WHERE departname like ?
      LIMIT ?,?`,
      [
        '%' + queryInfo.keywords + '%',
        parseInt(queryInfo.pageNum - 1) * queryInfo.pageSize,
        parseInt(queryInfo.pageSize),
      ]
    )

    return this.ctx.getRESTfulData(
      {
        total: resultAll.length,
        departmentList: result,
      },
      '获取筛选部门列表成功',
      200
    )
  }
  async getSingleDepartment(options) {
    console.log(options)
    let result = await this.app.mysql.select('c_department', {
      where: options,
    })
    console.log(result)
    return this.ctx.getRESTfulData(result, '获取单个部门成功', 200)
  }
  async createDepartment(departmentInfo) {
    const singleResult = await this.getSingleDepartment({
      departname: departmentInfo.departname,
    })

    if (singleResult.data.length > 0) {
      return this.ctx.getRESTfulData(null, '部门已存在', 401)
    }

    const result = await this.app.mysql.insert('c_department', {
      ...departmentInfo,
    })

    if (result.affectedRows === 1) {
      const singleResult2 = await this.getSingleDepartment({
        id: result.insertId,
      })

      return this.ctx.getRESTfulData(
        singleResult2.data[0],
        '新增部门列表成功',
        201
      )
    } else {
      return this.ctx.getRESTfulData(null, '新增部门列表失败', 401)
    }
  }
  async updateDepartment(departmentInfo, id) {
    const singleResult = await this.getSingleDepartment({
      departname: departmentInfo.departname,
    })

    if (singleResult.data.length > 0) {
      return this.ctx.getRESTfulData(null, '部门已存在', 401)
    }

    delete departmentInfo.id

    let result = await this.app.mysql.update('c_department', {
      ...departmentInfo,
      id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '部门更新成功',
          status: 201,
        },
      }
    }
  }
  async deleteDepartment(id) {
    let result = await this.app.mysql.delete('c_department', {
      id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '部门删除成功',
          status: 200,
        },
      }
    }
  }
}

module.exports = DepartmentService
